package com.bbx.taxi.client.Activity.login;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.SDK;
import com.bbx.api.sdk.model.official.passanger.Official_CodeBuild;
import com.bbx.api.sdk.model.official.passanger.Official_LoginBuild;
import com.bbx.api.sdk.model.official.passanger.Return.Official_Code;
import com.bbx.api.sdk.model.official.passanger.Return.Official_Login;
import com.bbx.api.sdk.model.passanger.CodeBuild;
import com.bbx.api.sdk.model.passanger.LoginBuild;
import com.bbx.api.sdk.model.passanger.Token;
import com.bbx.api.sdk.model.passanger.Return.Code;
import com.bbx.api.sdk.model.passanger.Return.Login;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.official.passanger.Official_CodeNet;
import com.bbx.api.sdk.net.official.passanger.Official_LoginNet;
import com.bbx.api.sdk.net.passeger.conn.CodeNet;
import com.bbx.api.sdk.net.passeger.conn.LoginNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Menu.ClauseActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.ClauseMsg;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.DB.Util.DBHelper;
import com.bbx.taxi.client.Service.LoginService;
import com.bbx.taxi.client.Util.DataCleanManager;
import com.bbx.taxi.client.Util.NetworkDetector;
import com.bbx.taxi.client.Util.Phone;
import com.bbx.taxi.client.Util.VersionInfo;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog;
import com.bbx.taxi.client.widget.Dailog.MyAlertDailog.onClickSingleListener;

public class LoginActivity extends BaseBBXActivity implements TextWatcher,OnFocusChangeListener {
	@InjectView(R.id.telephone)
	EditText telephone;
	@InjectView(R.id.code)
	EditText et_code;
	@InjectView(R.id.dynamic_code)
	Button dynamic_code;
	@InjectView(R.id.login)
	Button btn_login;
	@InjectView(R.id.tv_clause)
	TextView tv_clause;
	@InjectView(R.id.iv_tel_del)ImageView iv_tel_del;
	@InjectView(R.id.iv_code_del)ImageView iv_code_del;
	@InjectView(R.id.layout_recommend_code)RelativeLayout layout_recommend_code;
	@InjectView(R.id.et_recommend_code)EditText et_recommend_code;
	@InjectView(R.id.iv_recommend_code)ImageView iv_recommend_code;
	private Timer timer;
	private CodeTask mCodeTask;
	private LoginTask mLoginTask;
	private int intentType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		IsSwipeBack = false;
		setContentView(R.layout.login);
		super.onCreate(savedInstanceState);
		

	}

	@Override
	protected void initView() {
		setTitle(getString(R.string.login_title));
		MainAttribute main = MainAttribute.getInstance();
		if (getIntent().getExtras() != null) {
			intentType = getIntent().getExtras().getInt(MainMsg.extra_login);
		}
		if(MainActivity.mMenuDrawer!=null){
			MainActivity.mMenuDrawer.closeMenu(false);
		}
		Value.isUnSDK=false;
		DBHelper.mInstance=null;
		SDK.ins.mClient.disconnect(mApplication.getUid());
		stopService(new Intent(this, LoginService.class));
		DataCleanManager.cleanDatabases(context);
		DataCleanManager.cleanSharedPreference(context);
		mApplication.user_name="";
		mApplication.user_phone="";
//		DataCleanManager.cleanFiles(context);
//		DataCleanManager.cleanExternalCache(context);
		dynamic_code.setOnClickListener(this);
		btn_login.setOnClickListener(this);
		tv_clause.setOnClickListener(this);
		iv_tel_del.setOnClickListener(this);
		iv_code_del.setOnClickListener(this);
		iv_recommend_code.setOnClickListener(this);
		et_code.addTextChangedListener(this);
		telephone.setOnFocusChangeListener(this);
		et_code.setOnFocusChangeListener(this);
		telephone.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (s.length() == 11) {
					dynamic_code.setEnabled(true);
				} else {
					dynamic_code.setEnabled(false);
				}
				if (!s.toString().isEmpty()) {
					iv_tel_del.setVisibility(View.VISIBLE);
				} else {
					iv_tel_del.setVisibility(View.GONE);
				}
			}
		});
		et_recommend_code.addTextChangedListener(new TextWatcher() {
			  int index = 0;
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				if (!s.toString().isEmpty()) {
					iv_recommend_code.setVisibility(View.VISIBLE);
				} else {
					iv_recommend_code.setVisibility(View.GONE);
				}
			 	et_recommend_code.removeTextChangedListener(this);//解除文字改变事件
                 index = et_recommend_code.getSelectionStart();//获取光标位置
                 et_recommend_code.setText(s.toString().toUpperCase());//转换
                 et_recommend_code.setSelection(index);//重新设置光标位置
                 et_recommend_code.addTextChangedListener(this);//重新绑定事件
			}
		});
		// //启动登陆
		// GClientBox.instance().getClient().login(Config.srvip, Config.srvport,
		// Config.cliversion, 1,cid,pwd,token);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}

	/**
	 * 获取验证码
	 */
	private void onDynamicCode() {
		Official_CodeBuild mCodeBuild = new Official_CodeBuild(context);
		mCodeBuild.phone = telephone.getText().toString().trim();
		mCodeTask = new CodeTask(context, mCodeBuild);
		mCodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	public class CodeTask extends BaseAsyncTask {

		private Official_CodeBuild mCodeBuild;

		public CodeTask(Activity context, Official_CodeBuild mCodeBuild) {
			super(context,0);
			this.mCodeBuild = mCodeBuild;
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mCodeBuild).getJson();
			return new Official_CodeNet(context, json);
		}

		@Override
		public void onSuccess(Object object) {
			if (object != null) {
				Official_Code code=(Official_Code)object;
//				if(code.getFirstLogin()){
//					layout_recommend_code.setVisibility(View.VISIBLE);
//				}else{
//					layout_recommend_code.setVisibility(View.GONE);
//				}
				ToastUtil.showToast(context, R.string.get_success);
				dynamic_code.setEnabled(false);
				iv_tel_del.setVisibility(View.GONE);
				timer = new Timer();
				timer.schedule(new TimerTask() {
					int i = 60;

					// TimerTask 是个抽象类,实现的是Runable类
					@Override
					public void run() {

						// 定义一个消息传过去
						Message msg = new Message();
						msg.what = i--;
						mHandler.sendMessage(msg);
					}

				}, 1000, 1000);
				telephone.setEnabled(false);
				iv_tel_del.setEnabled(false);
			} else {
				ToastUtil.showToast(context, R.string.get_fial);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			// TODO Auto-generated method stub
			ToastUtil.showToast(context, getResources().getString(R.string.no_network));
		}
	}

	private class LoginTask extends BaseAsyncTask {

		private Official_LoginBuild mLoginBuild;

		public LoginTask(Activity context, Official_LoginBuild mLoginBuild) {
			super(context,0);
			this.mLoginBuild = mLoginBuild;
		}

		@Override
		public void onSuccess(Object object) {
			// TODO Auto-generated method stub
			if (object != null) {
				Official_Login login = (Official_Login) object;
				ToastUtil.showToast(context, R.string.login_success);
				mApplication.setUid(login.uid);
				mApplication.setToken(login.access_token);
//                Value.need_fetch_pic=login.getNeed_fetch_pic();
				Token token = new Token(context);
				token.uid = login.uid;
				token.access_token = login.access_token;
				SharedPreEncryptUtil.putStringEncryptValue(LoginActivity.this,
						SharedPreEncryptUtil.TokenAndUid, token);
				SharedPreUtil.putStringValue(LoginActivity.this,
						SharedPreEncryptUtil.phone, telephone.getText()
								.toString());
				SharedPreUtil.putBooleanValue(LoginActivity.this,
						SharedPreEncryptUtil.isLoadOrder_ing, true);
				mApplication.user_phone = telephone.getText().toString();
				mApplication.isFirstActivity = true;
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				intent.putExtra(MainMsg.extra_viewpageId, MainActivity.viewId);
				intent.putExtra(MainMsg.extra_success, MainMsg.LOGIN_SUCCESS);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				onfinish();
			} else {
				ToastUtil.showToast(context, R.string.login_fail);
			}

		}

		@Override
		public void onFailed(int status, String msg) {
			if(status==-3||status==-101){
				final MyAlertDailog dialog = new MyAlertDailog(LoginActivity.this.context);
				dialog.setTitle(getString(R.string.mydailog_title));
				dialog.setContent(getString(R.string.mydailog_content_no_register));
				dialog.setSingle(getString(R.string.mydailog_confirm));
				if (dialog != null && !dialog.isShowing()) {
					dialog.show();
				}
				dialog.setOnClickSingleListener(new onClickSingleListener() {
					@Override
					public void onClickSingle() {
						dialog.dismiss();
					}
				});
			}else{
				try {
					JSONObject jso=new JSONObject(msg);
					ToastUtil.showToast(context, jso.getString("message"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
	
//			if(status==-10104){
//				ToastUtil.showToast(context, R.string.code_error);
//			}else{
//				if(status==-3){
//					try {
//						JSONObject jso=new JSONObject(msg);
//						ToastUtil.showToast(context, jso.getString("message"));
//					} catch (JSONException e) {
//						e.printStackTrace();
//					}
//				}else{
//					ToastUtil.showToast(context, R.string.no_network);
//				}
//			
//			}

		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mLoginBuild).getJson();
			return new Official_LoginNet(context, json);
		}

	}

	/**
	 * 登陆
	 */
	public void onLogin() {
		Official_LoginBuild mLoginBuild = new Official_LoginBuild(context);
		mLoginBuild.phone = telephone.getText().toString();
		mLoginBuild.vcode = et_code.getText().toString();
		mLoginBuild.imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
				.getDeviceId();
		mLoginBuild.type="0";
		mLoginBuild.version=VersionInfo.getVersion(this);
		mLoginTask = new LoginTask(context, mLoginBuild);
		mLoginTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_left:
			if (intentType == MainMsg.INTENT_LOGIN) {
				onfinish();
			} else {
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				intent.putExtra(MainMsg.extra_quit, MainMsg.INTENT_QUIT);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				overridePendingTransition(0, 0);
				onfinish();
				overridePendingTransition(0, 0);
			}

			break;
		case R.id.dynamic_code:
			if (telephone.getText().toString().equals("")) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.phone_no_null), Toast.LENGTH_SHORT)
						.show();
				return;
			}
			if (!Phone.isPhoneNumberValid(telephone.getText().toString())) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.phone_format_error),
						Toast.LENGTH_SHORT).show();
				return;
			}
			onDynamicCode();
			break;
		case R.id.login:
			if (et_code.getText().toString().equals("")) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.code_no_null), Toast.LENGTH_SHORT)
						.show();
				return;
			}
			if (!Phone.isPhoneNumberValid(telephone.getText().toString())) {
				Toast.makeText(LoginActivity.this,
						getString(R.string.phone_format_error),
						Toast.LENGTH_SHORT).show();
				return;
			}
			if (et_recommend_code.getText().toString().length()>=4||et_recommend_code.getText().toString().equals("")) {
				
			}else{
				Toast.makeText(LoginActivity.this,
						getString(R.string.recommend_code_error),
						Toast.LENGTH_SHORT).show();
				return;
			}
			if(!NetworkDetector.detect(this)){
				ToastUtil.showToast(context, getResources().getString(R.string.no_network));
				return;
			}
			onLogin();
			break;
		case R.id.tv_clause:
			startActivity(new Intent(this,ClauseActivity.class).putExtra(ClauseMsg.extra_clause, ClauseMsg.CLAUSE_SERVICE));
			break;
		case R.id.iv_tel_del:
			telephone.setText("");
			break;
		case R.id.iv_code_del:
			et_code.setText("");
			break;
		case R.id.iv_recommend_code:
			et_recommend_code.setText("");
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	// 定义Handler
	final Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// handler处理消息
			if (msg.what > 0) {
				// 主要不要去的空格，空格是为了占字节
				dynamic_code.setText("       " + msg.what + getString(R.string.time_s)+"       ");
			} else {
				// 在handler里可以更改UI组件
				dynamic_code.setText(R.string.get_code);
				dynamic_code.setEnabled(true);
				telephone.setEnabled(true);
				iv_tel_del.setEnabled(true);
				timer.cancel();
			}
		}
	};

	protected void onResume() {
		// app 从后台唤醒，进入前台,不执行。
		Value.isActive=true;
		super.onResume();
	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	protected void onDestroy() {
		if (mCodeTask != null
				&& mCodeTask.getStatus() != AsyncTask.Status.FINISHED)
			mCodeTask.cancel(true);
		if (mLoginTask != null
				&& mLoginTask.getStatus() != AsyncTask.Status.FINISHED)
			mLoginTask.cancel(true);
		super.onDestroy();

	}

	@Override
	public void afterTextChanged(Editable s) {
		if (s.length() == 4 && telephone.getText().toString().length() == 11) {
			btn_login.setEnabled(true);
		} else {
			btn_login.setEnabled(false);
		}
		if (!s.toString().isEmpty()) {
			iv_code_del.setVisibility(View.VISIBLE);
		} else {
			iv_code_del.setVisibility(View.GONE);
		}

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (intentType == MainMsg.INTENT_LOGIN) {
				finish();
			} else {
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				intent.putExtra(MainMsg.extra_quit, MainMsg.INTENT_QUIT);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}

			return true;

		}
		return false;
	}

	@Override
	public void onFocusChange(View v, boolean focus) {
		if (v == et_code) {

			if (focus) {
				if (et_code.length() == 0) {
					iv_code_del.setVisibility(View.GONE);
				} else {
					iv_code_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_code_del.setVisibility(View.GONE);
			}
		} else if (v == telephone) {
			iv_tel_del.setVisibility(View.VISIBLE);
			if (focus) {
				if (telephone.length() == 0) {
					iv_tel_del.setVisibility(View.GONE);
				} else {
					iv_tel_del.setVisibility(View.VISIBLE);
				}
			} else {
				iv_tel_del.setVisibility(View.GONE);
			}
		}

	}
}
